package com.yyw.filter;

import com.alibaba.fastjson.JSON;
import com.yyw.bean.Employee;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        try {
            if (!request.getMethod().equals("POST")) {
                throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
            }else {
                //获取页面传过来的json数据，转化成employee对象
                Employee employee = JSON.parseObject(request.getInputStream(), Employee.class);

                System.out.println("从页面收到的账号信息：employee = " + employee);

                //把账号密码交给认证管理员来认证
                UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(employee.getUsername(), employee.getPassword());
                // Allow subclasses to set the "details" property
                setDetails(request, authRequest);
                return this.getAuthenticationManager().authenticate(authRequest);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return super.attemptAuthentication(request, response);
    }
}
